import { Component, Injector, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, Slides,Events } from 'ionic-angular';
import { BasePage } from '../../basePage';
import { StorageService } from './../../../providers/StorageService';
import { UserService } from './../../../providers/UserService';

declare var Swiper;
/**
 * Generated class for the FollowPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-follow',
  templateUrl: 'follow.html',
})
export class FollowPage extends BasePage {

  userinfo = {}//获取内存中的数据
  shopcount = 0;
  shopteachercount = 0;
  a
  swiper: any;
  @ViewChild('contentSlides') contentSlides: Slides;
  items: Array<any> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8];
  menus: Array<string> = ["美甲师", "店铺"]

  constructor(injector: Injector, public userService: UserService, public stc: StorageService,public events: Events) {
    super(injector);
    this.userinfo = this.stc.read('userinfo');
    this.getlunxun();
    events.subscribe('get',(j, time)=>{
      this.a=j
   })
  
  }

  ionViewDidLoad() {
    this.initSwiper();
  }



  /**初始化 */
  initSwiper() {
    this.swiper = new Swiper('.pageMenuSlides .swiper-container', {
      slidesPerView: 4,
      spaceBetween: 0,
      breakpoints: {
        1024: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        768: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        640: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        320: {
          slidesPerView: 4,
          spaceBetween: 0
        }
      }
    });
  }


  /**点击选择 */
  selectPageMenu($event, index) {
    this.setStyle(index);
    this.contentSlides.slideTo(index);
  }



  /**样式切换选中 */
  setStyle(index) {
    var slides = document.getElementsByClassName('pageMenuSlides')[0].getElementsByClassName('swiper-slide');
    if (index < slides.length) {
      for (var i = 0; i < slides.length; i++) {
        var s = slides[i];
        s.className = "swiper-slide";
      }
      slides[index].className = "swiper-slide bottomLine";
    }
  }

  /**上一个页面 */
  dismissCLI() {
    let id=[];  //最终id
    let id1=[]; //美甲师id
    let id2=[]; //美甲店id
    //因为缓存的数据为对象类型，所以要转为数组才能获取长度
    for(let i in this.stc.read("focuse1")){
      id1.push(this.stc.read("focuse1")[i])
    }
    for(let j in this.stc.read("focuse2")){
      id2.push(this.stc.read("focuse2")[j])
    }
    //分为4中情况，都有选择，都没选，选了美甲师，选了美甲店，而无效的选择有：没选和选了取消了（即有效的选择不能为null也不能长度为0）
    if(id1 == null || id1.length ==0){
      if(id2 == null || id2.length ==0){
        console.log("都没选")
      }else{
        console.log("选了美甲店")
        id=id2;
        this.focusAPI(id);
      }
    }else{
      if(id2 == null|| id2.length ==0){
        console.log("选了美甲师")
        id=id1
        this.focusAPI(id)
      }else{
        console.log("都选了")
        id=id.concat(id1,id2)
        this.focusAPI(id)
      }
    }
    console.log(id)
    //清空缓存
    this.viewCtrl.dismiss();
    this.stc.removeItem("focuse1");
    this.stc.removeItem("focuse2");
  }

  
  /**
   * 根据缓存得到的美甲师和美甲店id来取消关注
   * @param id 美甲师和美甲店的ID
   */
   async focusAPI(id) {
    let param = { "focused_id":id, 'user_id': this.userinfo['user_id'] };
    let loader = this.loadingCtrl.create({
      content: "",
    });
    let result = await this.userService.focusAPI(param);
    loader.dismiss();
    if (result.code == 1) {
      console.log("取消关注成功")
    } else {
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 2000,
        position: 'bottom',
      })
      toast.present();
    }
  }


  getlunxun(){
    this.getshopcount();
    this.getshopteachercount();
  }


  /**监视是否取消 */   /*为什么要用轮询的方式？？？*/
  // getlunxun() {
  //   let timeId = setInterval(() => {
  //     this.getshopcount();
  //     this.getshopteachercount();
  //   }, 1000);
  // }

  /**获取关注店铺总数 */
  getshopcount() {
    let param = { 'focus_type': '2', 'user_id': this.userinfo['user_id'] };
    this.getUserFocusAPI(param);
  }

  /**获取关注美甲师总数 */
  getshopteachercount() {
    let param = { 'focus_type': '1', 'user_id': this.userinfo['user_id'] };
    this.getUserFocusAPI(param);
  }
  /**滑动选择 */
  slideChanged() {
    let index = this.contentSlides.getActiveIndex();
    this.setStyle(index);
    this.swiper.slideTo(index, 300);
    // this.getlunxun();
  }
  async getUserFocusAPI(param) {
    let loader = this.loadingCtrl.create({
      content: "",
    });
    let result = await this.userService.getUserFocusAPI(param);
    loader.dismiss();
    if (result.code == 1) {
      if (param.focus_type == 2) {
        this.shopcount = result.data.count;
      } else {
        this.shopteachercount = result.data.count;
      }
    } else if (result.code == 0) {
      this.shopteachercount = this.shopcount = result.data.length;
    }
  }


}
